package com.power.impl;

import com.power.contant.AuthConstants;
import com.power.factory.LoginStrategyFactory;
import com.power.strategy.LoginStrategy;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Resource
    private LoginStrategyFactory loginStrategyFactory;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //从 web 依赖中获取http上下文的
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        HttpServletRequest request = requestAttributes.getRequest();
        String loginType = request.getHeader(AuthConstants.LOGIN_TYPE);

        if(!StringUtils.hasText(loginType)){
            throw new InternalAuthenticationServiceException("当前为非法登录，登录的类型不匹配");
        }

        //使用策略模式 和 工厂模式
        // 从请求头中获取登录类型 然后从工厂中创创建相应的登录类型
        LoginStrategy instance = loginStrategyFactory.getInstance(loginType);
        return instance.realLogin(username);
    }
}
